import 'dotenv/config';
import { query } from '../src/db/mysql.js';

function toSeconds(duration) {
  // duration like "4:29" or "03:59"
  if (!duration || typeof duration !== 'string') return null;
  const m = duration.match(/^(\d{1,2}):(\d{2})$/);
  if (!m) return null;
  const min = parseInt(m[1], 10);
  const sec = parseInt(m[2], 10);
  if (Number.isNaN(min) || Number.isNaN(sec)) return null;
  return min * 60 + sec;
}

function formatTimestamp(sec) {
  const m = Math.floor(sec / 60);
  const s = sec % 60;
  return `[${String(m).padStart(2, '0')}:${String(s.toFixed(2)).padStart(5, '0')}]`;
}

function buildPlaceholderLrc(title, artist, totalSeconds) {
  const lines = [];
  lines.push(`${formatTimestamp(0)} 歌曲：${title}`);
  lines.push(`${formatTimestamp(5)} 演唱：${artist}`);
  lines.push(`${formatTimestamp(10)} 本曲歌词为占位内容`);
  lines.push(`${formatTimestamp(20)} 请后续导入正版歌词替换`);
  const steps = totalSeconds ? Math.max(8, Math.min(12, Math.floor(totalSeconds / 20))) : 10;
  const interval = totalSeconds ? Math.max(10, Math.floor(totalSeconds / steps)) : 10;
  let t = 30;
  for (let i = 1; i <= steps; i++) {
    lines.push(`${formatTimestamp(t)} 占位段落 ${i}`);
    t += interval;
  }
  if (totalSeconds) {
    lines.push(`${formatTimestamp(Math.max(totalSeconds - 2, 0))} 占位结束`);
  } else {
    lines.push(`${formatTimestamp(t + 5)} 占位结束`);
  }
  return lines.join('\n');
}

async function main() {
  const rows = await query(
    "SELECT id, title, artist, duration FROM songs WHERE lyrics IS NULL OR lyrics = ''"
  );
  if (rows.length === 0) {
    console.log('No songs without lyrics. Nothing to do.');
    return;
  }
  let updated = 0;
  for (const r of rows) {
    const totalSeconds = toSeconds(r.duration);
    const lrc = buildPlaceholderLrc(r.title || '未知歌曲', r.artist || '未知歌手', totalSeconds);
    await query("UPDATE songs SET lyrics = ? WHERE id = ?", [lrc, r.id]);
    updated++;
  }
  console.log(`Filled placeholder lyrics for ${updated} songs.`);
}

main().catch(err => {
  console.error(err);
  process.exit(1);
});